package com.example.administrator.kaohedemo.Dispatcher;

import com.example.administrator.kaohedemo.Action.Action;
import com.example.administrator.kaohedemo.Store.Store;
import com.squareup.otto.Bus;

/**
 * Created by Administrator on 2016/6/20.
 */
public class Dispatcher {

    private static Dispatcher dispatcher;
    private Bus bus;

    public static Dispatcher getInstense(){
        if (dispatcher==null){
            dispatcher=new Dispatcher();
        }
        return dispatcher;
    }
    Dispatcher(){
        bus=new Bus();
    }

    public void register(Object object){
        bus.register(object);
    }

    public void unregister(Object object){
        bus.unregister(object);
    }

    public void StoreChanged(Store.StoreChanged ss){
        post(ss);
    }

    public void dispatch(String type,Object... object){

        if (isEmpty(type)) {
            throw new IllegalArgumentException("Type must not be empty");
        }

        if (object.length % 2 != 0) {
            throw new IllegalArgumentException("Object must be a valid list of key,value pairs");
        }

        Action.setType(type).build();
        Action.Builder builder=Action.setType(type);

        int i=0;
        while (i<object.length){
            String key= (String) object[i++];
            Object value=object[i++];
            builder.put(key,value);
        }

        post(builder.build());
    }

    private void post(Object o){
        bus.post(o);
    }

    private boolean isEmpty(String type) {
        return type == null || type.isEmpty();
    }
}
